<template>
  <div class="tools-page">
    <div class="container mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-4xl font-bold mb-4">工具库</h1>
        <p class="text-gray-600 dark:text-gray-400">
          浏览全部开发工具，找到最适合你的
        </p>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
        <!-- 侧边栏筛选 -->
        <aside class="lg:col-span-1">
          <div class="card p-6 sticky top-20">
            <h3 class="font-semibold mb-4">筛选条件</h3>

            <!-- 搜索 -->
            <div class="mb-6">
              <label class="block text-sm font-medium mb-2">搜索</label>
              <input
                v-model="filters.search"
                type="text"
                placeholder="输入关键词..."
                class="input"
                @input="handleFilterChange"
              />
            </div>

            <!-- 分类 -->
            <div class="mb-6">
              <label class="block text-sm font-medium mb-2">分类</label>
              <select
                v-model.number="filters.categoryId"
                class="input"
                @change="handleFilterChange"
              >
                <option :value="undefined">全部分类</option>
                <option
                  v-for="category in categories"
                  :key="category.id"
                  :value="category.id"
                >
                  {{ category.name }}
                </option>
              </select>
            </div>

            <!-- 价格筛选 -->
            <div class="mb-6">
              <label class="block text-sm font-medium mb-2">价格</label>
              <div class="space-y-2">
                <label class="flex items-center">
                  <input
                    type="radio"
                    v-model="priceFilter"
                    value="all"
                    class="mr-2"
                    @change="handleFilterChange"
                  />
                  全部
                </label>
                <label class="flex items-center">
                  <input
                    type="radio"
                    v-model="priceFilter"
                    value="free"
                    class="mr-2"
                    @change="handleFilterChange"
                  />
                  免费
                </label>
                <label class="flex items-center">
                  <input
                    type="radio"
                    v-model="priceFilter"
                    value="paid"
                    class="mr-2"
                    @change="handleFilterChange"
                  />
                  付费
                </label>
              </div>
            </div>

            <!-- 排序 -->
            <div class="mb-6">
              <label class="block text-sm font-medium mb-2">排序</label>
              <select
                v-model="filters.sortBy"
                class="input mb-2"
                @change="handleFilterChange"
              >
                <option value="createdAt">最新发布</option>
                <option value="views">浏览最多</option>
                <option value="upvotes">点赞最多</option>
                <option value="rating">评分最高</option>
              </select>
              <select
                v-model="filters.order"
                class="input"
                @change="handleFilterChange"
              >
                <option value="DESC">降序</option>
                <option value="ASC">升序</option>
              </select>
            </div>

            <!-- 重置按钮 -->
            <button @click="resetFilters" class="btn btn-secondary w-full">
              重置筛选
            </button>
          </div>
        </aside>

        <!-- 工具列表 -->
        <div class="lg:col-span-3">
          <!-- 结果统计 -->
          <div class="flex items-center justify-between mb-6">
            <p class="text-gray-600 dark:text-gray-400">
              共找到 <span class="font-semibold text-gray-900 dark:text-white">{{ total }}</span> 个工具
            </p>
          </div>

          <!-- 工具网格 -->
          <div v-if="pending" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div v-for="i in 9" :key="i" class="card p-6 animate-pulse">
              <div class="w-16 h-16 bg-gray-200 dark:bg-gray-700 rounded-lg mb-4"></div>
              <div class="h-6 bg-gray-200 dark:bg-gray-700 rounded mb-2"></div>
              <div class="h-4 bg-gray-200 dark:bg-gray-700 rounded"></div>
            </div>
          </div>

          <div v-else-if="tools && tools.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <ToolCard
              v-for="tool in tools"
              :key="tool.id"
              :tool="tool"
            />
          </div>

          <div v-else class="text-center py-16">
            <Icon name="heroicons:magnifying-glass" class="w-16 h-16 mx-auto text-gray-400 mb-4" />
            <p class="text-gray-500">未找到相关工具</p>
          </div>

          <!-- 分页 -->
          <div v-if="totalPages > 1" class="mt-8 flex justify-center">
            <div class="flex items-center gap-2">
              <button
                @click="goToPage(currentPage - 1)"
                :disabled="currentPage === 1"
                class="btn-ghost px-3 py-2 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <Icon name="heroicons:chevron-left" class="w-5 h-5" />
              </button>

              <button
                v-for="page in visiblePages"
                :key="page"
                @click="goToPage(page)"
                :class="[
                  'px-4 py-2 rounded-lg font-medium transition-colors',
                  page === currentPage
                    ? 'bg-primary-600 text-white'
                    : 'btn-ghost'
                ]"
              >
                {{ page }}
              </button>

              <button
                @click="goToPage(currentPage + 1)"
                :disabled="currentPage === totalPages"
                class="btn-ghost px-3 py-2 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <Icon name="heroicons:chevron-right" class="w-5 h-5" />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Category, ToolsResponse } from '~/types'

const route = useRoute()
const router = useRouter()
const { getTools } = useTools()
const { getCategories } = useCategories()

// 从 URL 查询参数初始化筛选条件
const filters = ref({
  page: route.query.page ? Number(route.query.page) : 1,
  limit: 18,
  categoryId: route.query.categoryId ? Number(route.query.categoryId) : undefined,
  search: (route.query.search as string) || '',
  sortBy: (route.query.sortBy as 'createdAt' | 'views' | 'upvotes' | 'rating') || 'createdAt',
  order: (route.query.order as 'ASC' | 'DESC') || 'DESC',
})

const priceFilter = ref('all') // 'all' | 'free' | 'paid'

// 获取分类列表
const { data: categories } = await useAsyncData<Category[]>('categories', () => getCategories())

// 获取工具列表
const { data: toolsData, pending, refresh } = await useAsyncData<ToolsResponse>(
  'tools',
  () => getTools(filters.value),
  { watch: [filters] }
)

const tools = computed(() => toolsData.value?.data || [])
const total = computed(() => toolsData.value?.total || 0)
const currentPage = computed(() => toolsData.value?.page || 1)
const totalPages = computed(() => toolsData.value?.totalPages || 1)

// 可见的页码
const visiblePages = computed(() => {
  const pages: number[] = []
  const maxVisible = 5
  let start = Math.max(1, currentPage.value - Math.floor(maxVisible / 2))
  let end = Math.min(totalPages.value, start + maxVisible - 1)
  
  if (end - start + 1 < maxVisible) {
    start = Math.max(1, end - maxVisible + 1)
  }
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  
  return pages
})

/**
 * 处理筛选变化
 */
const handleFilterChange = useDebounceFn(() => {
  filters.value.page = 1 // 重置到第一页
  updateURL()
  refresh()
}, 300)

/**
 * 跳转到指定页
 */
const goToPage = (page: number) => {
  if (page < 1 || page > totalPages.value) return
  filters.value.page = page
  updateURL()
  refresh()
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

/**
 * 重置筛选
 */
const resetFilters = () => {
  filters.value = {
    page: 1,
    limit: 18,
    categoryId: undefined,
    search: '',
    sortBy: 'createdAt',
    order: 'DESC',
  }
  priceFilter.value = 'all'
  updateURL()
  refresh()
}

/**
 * 更新 URL 查询参数
 */
const updateURL = () => {
  const query: any = {}
  if (filters.value.search) query.search = filters.value.search
  if (filters.value.categoryId) query.categoryId = filters.value.categoryId
  if (filters.value.page > 1) query.page = filters.value.page
  
  router.push({ query })
}

// 动态 SEO Meta 标签
const config = useRuntimeConfig()
const siteUrl = config.public.siteUrl || 'http://localhost:3000'

const seoTitle = computed(() => {
  let title = '工具库 - DevToolsHub | 开发者工具导航'
  if (filters.value.search) {
    title = `"${filters.value.search}" 搜索结果 - DevToolsHub`
  } else if (filters.value.categoryId && categories.value) {
    const category = categories.value.find(c => c.id === filters.value.categoryId)
    if (category) {
      title = `${category.name} 工具 - DevToolsHub`
    }
  }
  return title
})

const seoDescription = computed(() => {
  let desc = '浏览全部开发工具，包括前端框架、后端工具、AI工具、设计工具等多个分类。精选优质工具，提升开发效率。'
  if (filters.value.search) {
    desc = `搜索 "${filters.value.search}" 相关的开发工具，找到 ${total.value} 个结果。`
  } else if (filters.value.categoryId && categories.value) {
    const category = categories.value.find(c => c.id === filters.value.categoryId)
    if (category) {
      desc = `浏览 ${category.name} 分类下的所有开发工具，找到 ${total.value} 个优质工具。`
    }
  }
  return desc
})

const canonicalUrl = computed(() => {
  let url = `${siteUrl}/tools`
  if (filters.value.categoryId) {
    url += `?categoryId=${filters.value.categoryId}`
  }
  return url
})

useHead({
  title: seoTitle,
  meta: [
    { name: 'description', content: seoDescription },
    { name: 'keywords', content: '开发工具,工具导航,前端工具,后端工具,AI工具,设计工具,在线工具' },
    
    // Open Graph
    { property: 'og:type', content: 'website' },
    { property: 'og:title', content: seoTitle },
    { property: 'og:description', content: seoDescription },
    { property: 'og:url', content: canonicalUrl },
    
    // Twitter Card
    { name: 'twitter:card', content: 'summary' },
    { name: 'twitter:title', content: seoTitle },
    { name: 'twitter:description', content: seoDescription },
  ],
  link: [
    { rel: 'canonical', href: canonicalUrl },
  ],
})
</script>

